//------------------------------------------------------------------------------
// <copyright file="WinsockListeningSocket.h" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

#pragma once

#include <WinSock2.h>
#include "RpcChannelListener.h"

namespace Microsoft { namespace Internal { namespace GamesTest { namespace Rpc { namespace Server { namespace Ut {
	class WinsockListeningSocketTests;
}}}}}}

namespace Microsoft { namespace Internal { namespace GamesTest { namespace Rpc { namespace Server {

class WinsockListeningSocket : public RpcChannelListener
{
private: 
	HANDLE m_listeningLoopThread;

	bool m_isListening;
	SOCKET m_listenSocket;
	concurrency::critical_section s_synchronizationContext;

	// A flag indicating whether WSAStartup has been called.
	bool m_isSocketsInitialized;	

public:
	WinsockListeningSocket();
	virtual ~WinsockListeningSocket(void);

protected:
	GAMESTEST_ANNOTATE_HRESULT_METHOD HRESULT StartImpl(int port);
	GAMESTEST_ANNOTATE_HRESULT_METHOD HRESULT StopImpl();

	bool GetIsListening() const;

	/// <summary>
	/// Gets a value indicating whether or not this server has been started.
	/// </summary>
	__declspec(property(get=GetIsListening)) bool IsListening;

private:
	friend class Microsoft::Internal::GamesTest::Rpc::Server::Ut::WinsockListeningSocketTests;

	WinsockListeningSocket(const WinsockListeningSocket &) { }
	
	HRESULT CreateListeningSocket(int port, SOCKET & socket);	 
	__declspec(noinline) void CloseListeningSocket();

	DWORD Process();
	static DWORD ThreadStart(LPVOID instance);
};

}}}}}